package com.xxtx.trade.common.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <br>字符串处理工具类</br>
 *
 */
public class StringUtil {

    private static final Logger logger = LoggerFactory.getLogger(StringUtil.class);

    /**
     * 不同于String的valueOf，假如null返回null，否则返回对应字符
     *
     * @param obj 需要格式的对象
     * @return 格式后的字符
     */
    public static String valueOf(Object obj) {
        return (obj == null) ? null : obj.toString();
    }

    /**
     * Author huanghongwei
     *
     * @Date 2017/12/8 11:36
     */


    public static String[] trimSplit(String s, String delimiter) {

        String words[] = s.split(delimiter);
        int count = 0;
        for (int i = 0; i < words.length; i++) {
            if (words[i] == null || words[i].trim().length() == 0) {
                continue;
            } else {
                words[count] = words[i].trim();
                count++;
            }
        }

        String result[] = new String[count];
        System.arraycopy(words, 0, result, 0, count);
        return (result);
    }

    private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};

    public static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n = 256 + n;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String bytesToHexString(byte[] b) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            sb.append(byteToHexString(b[i]));
        }
        return sb.toString();
    }

    public static final byte[] hexStringToByte(String hex) {
        char[] chars = hex.toLowerCase().toCharArray();
        byte[] bytes = new byte[chars.length / 2];
        int byteCount = 0;
        for (int i = 0; i < chars.length; i += 2) {
            byte newByte = 0x00;
            newByte |= hexCharToByte(chars[i]);
            newByte <<= 4;
            newByte |= hexCharToByte(chars[i + 1]);
            bytes[byteCount] = newByte;
            byteCount++;
        }
        return bytes;
    }

    private static final byte hexCharToByte(char ch) {
        switch (ch) {
            case '0':
                return 0x00;
            case '1':
                return 0x01;
            case '2':
                return 0x02;
            case '3':
                return 0x03;
            case '4':
                return 0x04;
            case '5':
                return 0x05;
            case '6':
                return 0x06;
            case '7':
                return 0x07;
            case '8':
                return 0x08;
            case '9':
                return 0x09;
            case 'a':
                return 0x0A;
            case 'b':
                return 0x0B;
            case 'c':
                return 0x0C;
            case 'd':
                return 0x0D;
            case 'e':
                return 0x0E;
            case 'f':
                return 0x0F;
        }
        return 0x00;
    }

    public static boolean isStringDigital(String str) {
        String strt = str.trim();
        if (strt.length() == 0) {
            return false;
        }

        for (int i = 0; i < strt.length(); i++) {
            if (Character.isDigit(strt.charAt(i))) {
                continue;
            }
            return false;
        }
        return true;
    }


    public static byte[] getBytes(String s, String charset) {

        byte[] buf = null;

        if (s == null) {
            return (null);
        }

        if (charset == null || charset.length() == 0) {
            buf = s.getBytes();
        } else {
            try {
                buf = s.getBytes(charset);
            } catch (UnsupportedEncodingException e) {
                logger.error("get bytes error:charset=" + charset, e);
            }
        }

        return (buf);
    }

    public static String byteToString(byte buf[], String charset) {

        if (buf == null) {
            return ("");
        }
        if (charset == null || charset.length() == 0) {
            return new String(buf);
        } else {
            try {
                return new String(buf, charset);
            } catch (UnsupportedEncodingException e) {
                logger.error("byte2string unsupport charset:" + charset, e);
                return ("");
            }
        }
    }

    public static String getStackTrace(Throwable e) {
        StringBuffer exBuf = new StringBuffer(e.toString());
        StackTraceElement[] trace = e.getStackTrace();
        for (int i = 0; i < trace.length; i++) {
            exBuf.append("\nat ").append(trace[i]);
        }
        return exBuf.toString();
    }

    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 如果字符串是NULL，则返回空字符串，而不是"null"。否则返回原字符串
     */
    public static final String strNullToEmpty(final String str) {
        return str == null ? "" : str;
    }


    public static String mac2Str(byte[] mac) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < mac.length; i++) {
            sb.append(StringUtil.byteToHexString(mac[i]));
            if (i < mac.length - 1) {
                sb.append(":");
            }
        }
        return sb.toString();
    }

    public static byte[] Str2Mac(String macStr) {
        byte[] mac = StringUtil.hexStringToByte(macStr.replaceAll(":", ""));

        return mac;
    }

    public static byte[] Str2Ip(String IpStr) {
        byte[] ip = StringUtil.hexStringToByte(IpStr.replaceAll(".", ""));

        return ip;
    }

    public static String ip2Str(byte[] ip) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < ip.length; i++) {
            sb.append((ip[i]) & 0xff);
            if (i < ip.length - 1) {
                sb.append(".");
            }
        }
        return sb.toString();
    }

    public static String Byte2Utf8Str(byte[] bytes) {
        String retStr = "";
        if (bytes != null) {
            try {
                retStr = new String(bytes, "utf8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return retStr;
    }

    public static byte[] Str2Utf8Byte(String str, int bLen) {
        byte[] ret = new byte[bLen];
        int len = 0;
        try {
            byte[] strByte = str.getBytes("utf8");
            len = strByte.length;
            if (len > bLen) {
                len = bLen;
            }
            System.arraycopy(strByte, 0, ret, 0, len);

        } catch (UnsupportedEncodingException e) {
            logger.warn(StringUtil.getStackTrace(e));
        }

        return ret;
    }

    /*
     * byte数字转成String，忽略byte后的所有0
     */
    public static String bytes2String(byte[] bytes) {
        return (bytes2String(bytes, 0, bytes.length));
    }

    /**
     * 转换名字为字符串
     *
     * @param bytes
     * @param start
     * @param end
     * @return
     */
    public static String bytes2String(byte[] bytes, int start, int end) {
        if (bytes != null && bytes.length >= end && start >= 0 && start < end) {
            int tmp = start;
            while (tmp < end && bytes[tmp] != 0x00) {
                tmp++;
            }
            end = tmp;
            String res = null;
            try {
                res = new String(bytes, start, end - start, "UTF-8");
            } catch (Exception e) {
                logger.warn(StringUtil.getStackTrace(e));
            }
            return res;
        }
        return null;
    }

    /*
     * 判断字符串是否数字
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("^\\-?[0-9]+(\\.[0-9]+)?$");   //小数，负数都可以
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

//    public static void main(String[] args) {
//        System.out.println(StringUtil.isNumeric("20408112040750"));
//    }


    /**
     * 金额为null则返回0
     *
     * @param obj
     * @return
     */
    public static Long null2Zero(Long obj) {
        return (obj == null) ? 0 : obj;
    }

    /**
     * 为null则返回空字符串
     *
     * @param obj
     * @return
     */
    public static String null2Str(Object obj) {
        return (obj == null) ? "" : String.valueOf(obj);
    }

    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }

    public static String trim(Object str) {
        return str == null ? "" : str.toString().trim();
    }

    public static long getAsLong(String str) {
        return getAsLong(str, -1L);
    }

    public static long getAsLong(String str, long defaultv) {
        if (str != null && !"".equals(str)) {
            try {
                if (str.indexOf(".") >= 0) {
                    str = str.substring(0, str.indexOf("."));
                }
                return Long.parseLong(str, 10);
            } catch (Exception arg3) {
                return defaultv;
            }
        } else {
            return defaultv;
        }
    }

    public static int getAsInt(String str) {
        return getAsInt(str, -1);
    }

    public static int getAsInt(String str, int defaultv) {
        if (str != null && !"".equals(str)) {
            try {
                if (str.indexOf(".") >= 0) {
                    str = str.substring(0, str.indexOf("."));
                }
                return Integer.parseInt(str, 10);
            } catch (Exception arg2) {
                return defaultv;
            }
        } else {
            return defaultv;
        }
    }

    public static double getDouble(String str) throws Exception, NumberFormatException {
        return getDouble(str, 0.00D);
    }

    public static double getDouble(String str, double defaultValue) throws Exception, NumberFormatException {
        if ("".equals(str == null ? "" : str)) {
            return defaultValue;
        } else {
            try {
                return Double.parseDouble(str);
            } catch (NumberFormatException arg3) {
                return defaultValue;
            }
        }
    }
    /**
     * 是否包含中文
     * @param str
     * @return
     */
    public static boolean isContainChinese(String str) {

        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    /**
     * 校验字符串是否是数值(包含小数与负数)
     * 示例：
     * false : . 1. 1sr -  12. -12.
     * true: -12 -12.0 -12.056 12 12.0 12.056
     *
     * @param str 需要校验的字符串
     * @return false :不是数值 true：是数值
     */
    public static Boolean checkNumber(String str) {
        String regex = "^[0-9]\\d*$";
        boolean result=str.matches(regex);
        if (str == null || !str.matches(regex)) {
            return false;
        }
        return true;
    }
    /**
     * 判断是否为整数
     * @param str 传入的字符串
     * @return 是整数返回true,否则返回false
     */
    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }
    /**
     * 利用正则表达式判断字符串是否是数字
     * @param str
     * @return
     */
    public static boolean isNumeric1(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
    }
    public static boolean isNumeric3(String str)
    {
        final String number = "0123456789";
        for(int i = 0;i < number.length(); i ++)
        {
        if(number.indexOf(str.charAt(i)) == -1) {
            return false;
            }
        }
        return true;
    }
    public static boolean isNumeric00(String str)
    {
        try{
            Integer.parseInt(str);
            return true;
        }catch(NumberFormatException e) {
            System.out.println("异常：\"" + str + "\"不是数字/整数...");
            return false;
        }
    }
    public static boolean isNumeric4(String str)
    {
    for (int i = 0; i < str.length(); i++) {
        if (!Character.isDigit(str.charAt(i))) {
            return false;
            }
        }
            return true;
    }
    /**
     * 验证手机号码
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles){
        boolean flag = false;
        try{
            Pattern regex = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(17[0-9])|(18[0,5-9]))\\d{8}$");
            Matcher m = regex .matcher(mobiles);
            flag = m.matches();
        }catch(Exception e){
            flag = false;
        }
        return flag;
    }
    /**
     * 校验身份证
     *
     * @param idCard
     * @return 校验通过返回true，否则返回false
     */
    public static boolean isIDCard(String idCard) {
//        String REGEX_ID_CARD = "(^\\d{18}$)|(^\\d{15}$)";
        String REGEX_ID_CARD="(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{2}$)";
//        String REGEX_ID_CARD="^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$";
        return Pattern.matches(REGEX_ID_CARD, idCard);

    }
    public static boolean strIsNULL(String str){
        if ("null".equals(str)) {
            return true;
        }else if ("NULL".equals(str)){
            return true;
        }else if (!StringUtils.isNotEmpty(str)){
            return true;
        }
        return false;
    }
    public static boolean hasText(String str) {
        return !"".equals(nonNull(str));
    }

    public static String nonNull(String str) {
        return str == null ? "" : str;
    }

//    public static void main(String[] args) {
//        boolean bol=checkNumber("100");
//        if (bol){
//            System.out.println("boolean=true");
//        }else{
//            System.out.println("boolean=false");
//        }
//    }

}
